import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import renderModal, {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import { updatePayManagerUser } from '@/api/pay'
import type { FilterDto } from '@/render/FilterRender'
import type {
    CompanyInfoDto,
    PeriodInfoDto,
    PeriodInfoReqDto,
    WesureInfoDto
} from '@/api/company/types'
import { getReceiptData, goBack } from '@/utils/util'
import { getPeriodInsuranceCompanyList, getPeriodPlanList } from '@/api/insurance/company'
import type { OptionDto } from '@/components/low-code/types'
import { Button, message } from 'ant-design-vue'
import CustomTitle from '@/components/custom-title/Index'
import SuccessComponent from './SuccessComponent'
import { getDaliyInsuranceSolutionList } from '@/api/insurance/daily'
import type { OpenDailyReqDto } from '@/api/product/types'
import { ProductTypeEnum } from '@/const/enum'
import dayjs from 'dayjs'
import type { SaleReqDto } from '@/api/deal/types'
import { addContact, editContact } from '@/api/deal'
import { openDailyInsurance } from '@/api/product'
import { getWesureInfo } from '@/api/company'
import type { DictionaryDto } from '@/api/types'

@Component({
    expose: ['getData']
})
export class OpenDaily extends Render {
    @Prop() companyBasicInfo!: CompanyInfoDto

    showRecharge = false
    isSuccess = false

    basicData = {} as WesureInfoDto

    // get periodCompanyTypeListValue() {
    //     const data = getModelValue(this.basicFormConfig)
    //     return data.periodCompanyTypeList
    // }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('basicData')
    async handleWatch() {}

    // @Watch('periodCompanyTypeListValue')
    // async handleWatchPeriodCompanyTypeList(val: string[]) {
    //     let options = [] as OptionDto[]
    //     if (val?.length) {
    //         const res = (
    //             await getPeriodPlanList({
    //                 insureCompanys: val.join(',')
    //             })
    //         ).map((item) => ({
    //             label: item.dictLabel,
    //             value: item.remark,
    //             disabled: false
    //         }))

    //         console.log(321312312, res)

    //         res.forEach((i) => {
    //             i.disabled = this.basicData.periodPlanTypeList.includes(i.value as string)
    //         })
    //         options = res
    //     }
    //     this.basicFormConfig.items.periodPlanTypeList.options = options
    // }

    basicFormConfig = this.initFormConfig() as FormModalDto
    initFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                saleId: {
                    name: '所属销售',
                    element: 'select',
                    optionsType: 'saleList',
                    required: true
                },
                channelId: {
                    name: '收款渠道',
                    element: 'select',
                    optionsType: 'channel',
                    required: true,
                    callback: {
                        change: async (value: number) => {
                            this.basicFormConfig.items.receiptId.value = ''
                            if (value) {
                                this.basicFormConfig.items.receiptId.options =
                                    await getReceiptData(value)
                            } else {
                                this.basicFormConfig.items.receiptId.options = []
                            }
                        }
                    }
                },
                receiptId: {
                    name: '收款账号',
                    element: 'select',
                    required: true
                },
                creditCodePicture: {
                    name: '营业执照',
                    element: 'upload',
                    params: {
                        autoUpload: false,
                        accept: '.png,.jpg,.jpeg',
                        listType: 'text'
                    }
                }
            },
            complete: async () => {
                const data = getModelValue(this.basicFormConfig)
                await updatePayManagerUser(data)
                message.success('更新成功')
                this.basicFormConfig.show = false
            },
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {}
        } as FormModalDto
    }
    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    planFormConfig = this.initPlanFormConfig() as FormModalDto
    initPlanFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                insureCompanyType: {
                    name: '保险公司',
                    element: 'select',
                    optionsType: 'daliyInsuranceCompany',
                    params: {
                        clearable: false
                    },
                    required: true,
                    callback: {
                        change: async (value: string) => {
                            this.planFormConfig.items.insureTypeList.value = []
                            this.planFormConfig.items.insureTypeList.options = value
                                ? await this.insureTypeList(value)
                                : []
                        }
                    }
                },
                insureTypeList: {
                    name: '投保方案',
                    element: 'select',
                    params: {
                        clearable: false
                    },
                    multiple: true,
                    required: true
                }
            },
            complete: async () => {
                const data = getModelValue(this.basicFormConfig)
                await updatePayManagerUser(data)
                message.success('更新成功')
                this.planFormConfig.show = false
            },
            cancel: () => {
                this.planFormConfig.show = false
            },
            init: () => {}
        } as FormModalDto
    }
    planForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    async insureTypeList(insureCompany: string) {
        return (
            await getDaliyInsuranceSolutionList({
                insureCompany
            })
        ).map((item) => {
            item.label = item.dictLabel
            item.value = item.dictValue
            return item
        })
    }

    filterBtnConfig() {
        return {} as FilterDto
    }

    async onSubmit() {
        await this.basicForm.validate()
        await this.planForm.validate()
        const basicFormData = getModelValue(this.basicFormConfig)
        const planFormData = getModelValue(this.planFormConfig)
        const { saleId, creditCodePicture, ...otherData } = basicFormData
        const params = {
            id: this.basicData.companyId,
            isOpenWesure: 1,
            ...otherData,
            ...planFormData
        } as OpenDailyReqDto

        params.creditCodePicture =
            creditCodePicture?.[0]?.url ?? creditCodePicture?.[0]?.base64 ?? ''

        const saleParams = {
            companyId: this.basicData.companyId,
            id: this.basicData.dealId,
            productType: ProductTypeEnum.DALIY,
            saleId: saleId,
            serviceStartTime: dayjs().startOf('day').format('YYYY-MM-DD'),
            serviceState: 0
        } as SaleReqDto

        await openDailyInsurance(params)

        if (!this.basicData.saleId) {
            await addContact(saleParams)
        } else {
            await editContact({
                ...saleParams,
                saleOldId: this.basicData.saleId
            })
        }
        message.success('更新成功')
        this.isSuccess = true
        // this.handleRefresh()
    }

    onShowRecharge() {
        this.showRecharge = true
        // this.rechargeFormConfig.title = `${this.companyBasicInfo.companyName}子弹发薪充值窗口`
        // this.rechargeFormConfig.show = true
    }

    async initData() {
        const res = await getWesureInfo({ companyId: this.companyBasicInfo.companyId })
        this.basicData = res
        if (this.basicData.channelId) {
            this.basicFormConfig.items.receiptId.options = await getReceiptData(
                this.basicData.channelId
            )
        }
        // 整理后端给的投保方案
        if (this.basicData.insureType) {
            this.basicData.insureTypeList = JSON.parse(this.basicData.insureType).map(
                (i: DictionaryDto) => {
                    return i.dictValue
                }
            )
        }
        // 根据 保险公司获取投保方案列表
        if (this.basicData.insureCompanyType) {
            this.planFormConfig.items.insureTypeList.options = await this.insureTypeList(
                this.basicData.insureCompanyType
            )
        }

        initModelValue(this.basicFormConfig, this.basicData)

        if (this.basicData.isOpenWesure) {
            initModelValue(this.planFormConfig, this.basicData)
        }
    }

    async created() {
        this.basicForm = renderForm(this.basicFormConfig)
        this.planForm = renderForm(this.planFormConfig)
        await this.initData()
    }

    renderStatistics() {
        return <></>
    }

    renderRightBtns() {
        return <></>
    }

    render() {
        return this.isSuccess ? (
            <div class="h-full flex justify-center items-center">
                <SuccessComponent hint="已成功开通了日日保产品，需要继续添加方案，可在保险客户中心添加" />
            </div>
        ) : (
            <div class="flex flex-col h-full">
                <div class="flex-1">
                    <CustomTitle>开通日日保</CustomTitle>
                    <div class="pt-20px">{this.basicForm.element()}</div>
                    <CustomTitle>添加方案</CustomTitle>
                    <div class="pt-20px">{this.planForm.element()}</div>
                </div>
                <div class="pt-19px flex justify-center gap-20px">
                    <Button onClick={goBack}>取消</Button>
                    <Button type="primary" onClick={this.onSubmit}>
                        确认
                    </Button>
                </div>
            </div>
        )
    }
}

export default toNative<{ companyBasicInfo?: CompanyInfoDto }, { refresh: () => void }>(OpenDaily)
